package com.mgs.tagger.appdata
{
	import com.mgs.tagger.appdata.dto.DirectoryDTO;
	import com.mgs.tagger.appdata.dto.FileItemDTO;
	import com.mgs.tagger.appdata.dto.MainDTO;
	import com.mgs.tagger.appdata.dto.TagDTO;
	import com.mgs.tagger.appdata.dto.WorkspaceDTO;
	import com.mgs.tagger.log.Level;
	import com.mgs.tagger.log.Logger;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.registerClassAlias;

	public class PersistenceManager
	{
		private static var _instance:PersistenceManager;
		
		public static function get instance():PersistenceManager{
			if(_instance == null){
				_instance = new PersistenceManager();
			}
			return _instance;
		}
		
		private static const PREFERENCE_FILE:String = "preferences.dat";
		private var registered:Boolean = false;
		
		function PersistenceManager()
		{
		}
		public function load():MainDTO{
			register();
			var main:MainDTO;
			var file:File = getFile();
			if(file.exists){
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.READ);
				var unknownObject:Object = stream.readObject();
				stream.close();
				
				if(unknownObject is MainDTO){
					// version 2
					main = unknownObject as MainDTO;
				}else if(unknownObject is WorkspaceDTO){
					// version 1
					main = DtoFactory.createMain();
					var oldWorkspace:WorkspaceDTO = unknownObject as WorkspaceDTO;
					var newWorkspace:WorkspaceDTO = DtoFactory.createWorkspace();
					newWorkspace.name = "unnamed workspace";
					newWorkspace.itemSize = oldWorkspace.itemSize;
					newWorkspace.directories = oldWorkspace.directories;
					main.workspaces.push(newWorkspace);
					main.currentWorkspace = newWorkspace;
					for each(var tag:TagDTO in oldWorkspace.tags){
						tag.children = new Vector.<TagDTO>();
						tag.exclusive = false;
						tag.virtual = false;
						tag.mandatory = false;
						main.currentWorkspace.classification.children.push(tag);
					}
				}else{
					Logger.instance.log(Level.SEVERE, "unknown type ");
				}
			}else{
				main = DtoFactory.createMain();
			}
			return main;
		}
		public function save(main:MainDTO):void{
			register();
			var file:File = getFile();
			var stream:FileStream = new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeObject(main);
			stream.close();
		}
		private function register():void{
			if(!registered){
				registerClassAlias("MainDTO", MainDTO);
				registerClassAlias("workspaceDTO", WorkspaceDTO);
				registerClassAlias("DirectoryDTO", DirectoryDTO);
				registerClassAlias("FileItemDTO", FileItemDTO);
				registerClassAlias("TagDTO", TagDTO);
				registered = true;
			}
		}
		private function getFile():File{
			return File.applicationStorageDirectory.resolvePath(PREFERENCE_FILE);
		}
		
	}
}